﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Web.Enhancements.Rest
{
    [Serializable()]
    internal class ParameterUrlFormatter : ParameterFormatter
    {
        public ParameterUrlFormatter()
        {
        }

        public static ParameterUrlFormatter CreateInstance(System.Reflection.MethodInfo initializer)
        {
            ParameterUrlFormatter formatter = (ParameterUrlFormatter)ParameterFormatter.CreateInstance(typeof(ParameterUrlFormatter), initializer);
            return formatter;
        }

        public override void Initialize(System.Reflection.MethodInfo initializer)
        {
            this.methodInfo = initializer;
        }

        public override string FormatParameters(object[] parameters)
        {
            ParameterInfo[] pis = this.methodInfo.GetParameters();

            if (pis.Length != parameters.Length)
                throw new WebRestException(ErrorMessages.ResourceManager.GetString("NumberOfParametersMismatched"), pis.Length.ToString(), this.methodInfo.Name, parameters.Length.ToString());

            List<string> urlParams = new List<string>();

            Type type = null;
            object item = null;
            string urlValue = "";
            for (int ii = 0; ii < parameters.Length;ii++ )
            {
                item = parameters[ii];
                type = item.GetType();
                if (type.IsEnum)
                    urlValue = Convert.ChangeType(item, type.GetEnumUnderlyingType()).ToString();
                else if (type.IsPrimitive)
                {
                    switch (type.Name)
                    {
                        case "Char":
                        case "DateTime":
                        case "DateSpan":
                            urlValue = System.Web.HttpUtility.UrlEncode(item.ToString());
                            break;
                        default:
                            urlValue = item.ToString();
                            break;
                    }
                }
                else
                    urlValue = System.Web.HttpUtility.UrlEncode(item.ToString());
                urlParams.Add(string.Format("{0}={1}", pis[ii].Name, urlValue));
            }

            return string.Join("&", urlParams.ToArray());
        }
    }
}
